import React, { useEffect, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';

const MapComponent = () => {
    const [map, setMap] = useState(null);
    const [position, setPosition] = useState(null);
    const [address, setAddress] = useState('');

    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "83bc0e288beb6232bc0336b1901f36ba",
          };

        AMapLoader.load({
            key: '1eb29d5bd147edac9a898c41ff00cbba', // 高德地图API Key
            version: '2.0', // 指定要加载的 JSAPI 的版本
            plugins: ['AMap.Geolocation', 'AMap.Geocoder'], // 需要使用的的插件列表
            // securityJsCode: '83bc0e288beb6232bc0336b1901f36ba', // 替换为你的安全密钥

        })
            .then((AMap) => {
                const mapInstance = new AMap.Map('map-container', {
                    zoom: 15, // 初始化地图层级
                });

                // 使用高德地图的Geolocation插件获取用户当前位置
                const geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                    timeout: 10000, // 超过10秒后停止定位，默认：5s
                    buttonPosition: 'RB', // 定位按钮的停靠位置
                    buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点
                });

                mapInstance.addControl(geolocation);

                geolocation.getCurrentPosition(async (status, result) => {
                    if (status === 'complete') {
                        const { position } = result;
                        setPosition(position);

                        mapInstance.setCenter(position); // 将地图中心设置为用户当前位置

                        // 使用逆地理编码获取地区信息
                        const geocoder = new AMap.Geocoder();
                        
                        geocoder.getAddress(position, (status, geocodeResult) => {
                            console.log('逆地理编码结果:', geocodeResult); // 打印结果
                            if (status === 'complete' && geocodeResult.info === 'OK') {
                                const { formattedAddress, addressComponent } = geocodeResult.regeocode;
                                setAddress(
                                    `地址: ${formattedAddress}, 省份: ${addressComponent.province}, 城市: ${addressComponent.city}, 区县: ${addressComponent.district}`
                                );
                            } else {
                                console.error('逆地理编码失败', geocodeResult);
                            }
                        });
                    } else {
                        console.error('定位失败', result);
                    }
                });

                setMap(mapInstance);
            })
            .catch((e) => {
                console.error('地图加载失败', e);
            });
    }, []);

    return (
        <div>
            <div id="map-container" style={{ width: '100%', height: '5rem' }}></div>
            {position && (
                <div>
                    <p>当前位置: 纬度 {position.lat}, 经度 {position.lng}</p>
                    {address && <p>{address}</p>}
                </div>
            )}
        </div>
    );
};

export default MapComponent;